// Copyright (C) 2005 Taylor L. Riché <riche@cs.utexas.edu>
//  
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software 
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// 	$Id: ProcUnit.cc 138 2005-08-13 04:36:38Z richetl $	
//

#include "ProcUnit.hh"

using namespace lee;

ProcUnit::ProcUnit(Scheduler * s) : scheduler(s)
{
  MethodWrapper<ProcUnit> * mw = new MethodWrapper<ProcUnit>;
  mw->object = this;
  mw->method = &ProcUnit::process;
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  if(pthread_create(&coreThread, &attr, plainFunction, (void *)mw)) {
    std::cerr << "pthread_create failed" << std::endl;
    std::exit(1);
  }
}

ProcUnit::~ProcUnit()
{
  pthread_cancel(coreThread);
}

void
ProcUnit::executePCon(PCon * pcon) 
{
  pconQueue.push(pcon);
}

void
ProcUnit::process()
{
  Synchronized::Scope mutex(this);
  while(ag == NULL) {
    wait();
  }
  while(true) {
    PCon * currPCon = pconQueue.pop();
    PPFunction * currFunction = currPCon->getPPFunction();
    PktData * currData = currPCon->getPacket();
    std::pair<std::list<FuncExit *> *, std::list<Event *> *> p = currFunction->processDataWrapper(currData);
    std::list<FuncExit *> * exitList = p.first;
    std::list<Event *> * eventList = p.second;
    for(std::list<FuncExit *>::iterator i = exitList->begin();
	i != exitList->end(); i++) {
      if((*i)->pkt != NULL) {
	PCon * newPCon = new PCon();
	newPCon->setPPFunction(ag->getNextPPFunction(currFunction->getName(),(*i)->exit));
	newPCon->setPacket((*i)->pkt);
	ProcUnit * nextProc = scheduler->getProcUnit(newPCon);
	nextProc->executePCon(newPCon);
      }
      delete *i;
    }
    for(std::list<Event *>::iterator i = eventList->begin();
	i != eventList->end(); i++) {
      EventWrapper * newWrapper = new EventWrapper;
      newWrapper->master = NULL;
      newWrapper->ev = *i;
      scheduler->getCU()->deliver(newWrapper);
    }
    delete exitList;
    delete eventList;
    delete currPCon;
  }
};

